<?php

class wms_ctl_admin_logistImport extends desktop_controller
{
    /*
     * 快递揽件列表
     */
    
    function index(){

        $base_filter = array( '1'=>'1' );
        $this->finder('wms_mdl_logistImport',array(
            'title'=>'快递揽件导入列表',
            'actions' => array(
                //array('label'=>'导出模板','href'=>'index.php?app=ome&ctl=admin_order_groupon&act=exportOrderTemplate','target'=>'_blank')
            ),
            'use_buildin_new_dialog' => false,
            'use_buildin_set_tag'=>false,
            'use_buildin_recycle'=>false,
            'use_buildin_export'=>true,
            'use_buildin_import'=>false,
            'use_buildin_filter'=>true,
            'base_filter' => $base_filter,
             //'orderBy' =>'order_groupon_id DESC'
            ));

    }

    function import(){
        
        echo $this->page('admin/delivery/import.html');
    }

    function doImport(){
        if(!$_POST['groupon_name']){
            echo json_encode(array('result' => 'fail', 'msg' => array('导入标题不能为空')));
            return false;
        }
        $return = $this->_localSaveFile();
        $data = $return['data'];
        if(!$data){
            echo json_encode(array('result' => 'fail', 'msg' => array($return['res'])));
            return false;
        }

        $op_id = $this->user->get_id();
        $desktopMdl = app::get('desktop')->model('users');
        $logistMdl = app::get('wms')->model('logistImport');
        $deliveryMdl = app::get('wms')->model('delivery');
        $odeliveryMdl = app::get('ome')->model('delivery');

        $opt_name = $desktopMdl ->getList('name',array('user_id'=>$op_id));

        foreach ($data as $r => $row) {
            $data[$r]['1'] = str_replace(' ', '', $row['1']);
            $data[$r]['2'] = str_replace(' ', '', $row['2']);
        }
        $logistdata = array();
        foreach ($data as $key => $value) {
            if(!$value['1']){
                echo json_encode(array('result' => 'fail', 'msg' => array('快递单号不能为空')));
                return false;
            }

            $filter = array('logi_no' => $value['1']);
            $deliveryId = $odeliveryMdl ->getList('delivery_id',$filter);
            if(!$deliveryId){
                echo json_encode(array('result' => 'fail', 'msg' => array($value['1'].'物流单号系统不存在')));
                return false;
            }

            if (!$value['2']) {
                echo json_encode(array('result' => 'fail', 'msg' => array('揽件状态不能为空')));
                return false;
            }else if($value['2'] !== '已揽件' && $value['2'] !== '未揽件' && $value['2'] !== '已签收'){
                echo json_encode(array('result' => 'fail', 'msg' => array('揽件状态填写错误')));
            }

            if (!$value['3']) {
                echo json_encode(array('result' => 'fail', 'msg' => array('时间不能为空')));
                return false;
            }else{

            }
            $logistdata[$key]['name'] = $_POST['groupon_name'];
            if($value['2'] == '已揽件'){
                $logistdata[$key]['status'] = 1;
            }else if($value['2'] == '已签收'){
                $logistdata[$key]['status'] = 3;
            }else if ($value['2'] == '未揽件') {
                $logistdata[$key]['status'] = 2;
            }
            $logistdata[$key]['logi_no'] = $value['1'];
            $logistdata[$key]['create_time'] = strtotime($value['3']);
            $logistdata[$key]['opt_id'] = $op_id;
            $logistdata[$key]['opt_name'] = $opt_name['0']['name'];

        }
        foreach ($logistdata as $k => $v) {


            $filter = array('logi_no' => $v['logi_no']);
            $deliveryBn = $odeliveryMdl ->getList('delivery_bn',$filter);

            $delivery_time = $deliveryMdl ->getList('delivery_time,embrace_time,logistStatus',array('outer_delivery_bn'=>$deliveryBn[0]['delivery_bn']));
            if ($delivery_time[0]['logistStatus'] == '3') {
            	echo json_encode(array('result' => 'fail', 'msg' => array('该物流已签收')));
                return false;
            }

            if ($v['status'] == '1') {

                //$delivery_time = $deliveryMdl ->getList('delivery_time',array('outer_delivery_bn'=>$deliveryBn[0]['delivery_bn']));
                if ($delivery_time[0]['delivery_time'] > $v['create_time']) {
                    echo json_encode(array('result' => 'fail', 'msg' => array('揽件时间不能小于发货时间')));
                    return false;
                }
                //揽件时间更新数据
                $data_embrace = array('logistStatus' => $v['status'],'embrace_time' => $v['create_time']);
                $resultdeli = $deliveryMdl->update($data_embrace,array('outer_delivery_bn'=>$deliveryBn[0]['delivery_bn']));
            }elseif ($v['status'] == '3') {


                if ($delivery_time[0]['delivery_time'] > $v['create_time'] || $delivery_time[0]['embrace_time'] > $v['create_time']) {
                    echo json_encode(array('result' => 'fail', 'msg' => array('签收时间不能小于揽件时间')));
                    return false;
                }

                //签收时间更新数据
                $data_sign = array('logistStatus' => $v['status'],'sign_time' => $v['create_time']);
                $resultdeli = $deliveryMdl->update($data_sign,array('outer_delivery_bn'=>$deliveryBn[0]['delivery_bn']));
            }else{

                $data = array('logistStatus' => $v['status']);
                $resultdeli = $deliveryMdl->update($data,array('outer_delivery_bn'=>$deliveryBn[0]['delivery_bn']));
            }    
            $resultlogi = $logistMdl->save($v);
        } 

        if($resultdeli && $resultlogi){

            echo json_encode(array('result' => 'succ', 'msg' => '上传成功'));
            return;
        }else{
            return false;
        }

    }


    function exportOrderTemplate(){
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=".date('Ymd').".csv");
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        $title1 = $this->exportTemplate();
        echo '"'.implode('","',$title1).'"';

    }

    function exportTemplate(){
        $arr = array('*:序列号','*:快递单号','*:状态','*:时间');
        foreach ($arr as $v){
            $title[] = kernel::single('base_charset')->utf2local($v);
        }
        return $title;
    }

    private function _localSaveFile(){
       if( !$_FILES['import_file']['name'] ){
            return  kernel::single('ome_func')->getErrorApiResponse("未上传文件");
        }
        $tmpFileHandle = fopen( $_FILES['import_file']['tmp_name'],"r" );
       
        $mdl = $_POST['model'];
        $app_id = $_POST['app'];

        $oIo = kernel::servicelist('desktop_io');
        foreach( $oIo as $aIo ){
            if( $aIo->io_type_name == substr($_FILES['import_file']['name'],-3 ) ){
                $oImportType = $aIo;
                break;
            }
        }
        unset($oIo);
        if( !$oImportType ){
            return  kernel::single('ome_func')->getErrorApiResponse("导入格式不正确");
        }
        
        $contents = array();
        $oImportType->fgethandle($tmpFileHandle,$contents);
       // $newFileName = $app_id.'_'.$mdl.'_'.$_FILES['import_file']['name'].'-'.time();
 
       // base_kvstore::instance($app_id.'_'.$mdl)->store($newFileName,serialize($contents));
       // base_kvstore::instance($app_id.'_'.$mdl)->store($newFileName.'_sdf',serialize(array()));
      //  base_kvstore::instance($app_id.'_'.$mdl)->store($newFileName.'_error',serialize(array()));

        fclose($tmpFileHandle);
        unset($contents[0]);
        
        $tm_contents = array();
        foreach($contents as $row){
            if(!empty($row[0])){
                $tm_contents[] = $row;
            }
        }
        $contents = $tm_contents;
       
        if(empty($contents)){
            return  kernel::single('ome_func')->getErrorApiResponse("导入数据项为空");
        }else{
            return  kernel::single('ome_func')->getApiResponse($contents);
        }
    }


}